<template>
  <div class="flex">
    <div class="tableManage w-100%">
      <ContentWrap>
        <div class="search-form">
          <Search
            :schema="allSchemas.searchSchema"
            @reset="setSearchParams"
            @search="setSearchParams"
          />
        </div>

        <ElDivider />

        <!-- <div class="mb-10px">

         <BaseButton class="opBtn" size="" type="primary" @click="AddAction"
            >新增</BaseButton
          >
          <el-upload
            ref="uploadRef"
            class="opBtn-upload"
            :auto-upload="false"
            :show-file-list="false"
            :accept="'.xlsx,.xls'"
            :on-change="handleFileChange"
          >
             <BaseButton class="opBtn" size="" type="primary">
              导入
            </BaseButton>
          </el-upload>
          <BaseButton class="opBtn" size="" type="primary" @click="exportAction"
            >导出</BaseButton>
        </div> -->
        <Table
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :columns="allSchemas.tableColumns"
          :data="dataList"
          :loading="loading"
          @register="tableRegister"
          :pagination="{
            total,
          }"
        />
      </ContentWrap>
    </div>
    <Dialog width="65%" v-model="dialogVisible" :title="dialogTitle">
      <Write
        class="opWrite"
        v-if="actionType !== 'detail'"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
        :current-node-name="currentNodeName"
      />

      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
      />

      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          保存
        </BaseButton>
        <BaseButton @click="dialogVisible = false"> 关闭 </BaseButton>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="tsx">
import { directAxios } from "@/axios/index";
import {
  ref,
  unref,
  reactive,
  watch,
  computed,
  onMounted,
  defineProps,
  withDefaults,
  ComponentRef,
} from "vue";
import { ContentWrap } from "@/components/ContentWrap";
import { Table } from "@/components/Table";
import { ElMessage, ElMessageBox, ElUpload, UploadFile,  UploadInstance } from "element-plus";
import * as XLSX from 'xlsx';
import { getDictionary, getDictionaries } from "@/utils/options";

import { useTable } from "@/hooks/web/useTable";
import { Search } from "@/components/Search";
import Write from "./components/domesticSoftwareWrite.vue";
import { useValidator } from "@/hooks/web/useValidator";

import Detail from "./components/domesticSoftwareDetail.vue";
import { Dialog } from "@/components/Dialog";
import { CrudSchema, useCrudSchemas } from "@/hooks/web/useCrudSchemas";
import { BaseButton } from "@/components/Button";
import { useDictionaryStore } from "@/store/modules/dictionaryStore";
import { useDeviceTreeStore } from "@/store/modules/deviceTreeStore";
import { Edit, View, Delete } from "@element-plus/icons-vue";
import axios from "axios";
import { debounce } from 'lodash-es'

const { required } = useValidator();
const dictionaryStore = useDictionaryStore();

const deviceTreeStore = useDeviceTreeStore();
const prop = withDefaults(
  defineProps<{
    currentNode: string;
  }>(),
  {
    currentNode: "",
  }
);
const currentNodeName = ref("");

// 从store中获取当前节点key
const currentNodeKey = ref(deviceTreeStore.currentNodeKey);



const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState;
    // 确保使用 store 中的 currentNodeKey
    const deviceCode = deviceTreeStore.currentNodeKey;

    if (!deviceCode) {
      return {
        list: [],
        total: 0,
      };
    }
    const res = await "/cDomesticSoftwares/page".get({
      deviceCode: deviceCode,
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      isLockTask:0,
      ...unref(searchParams),
    });
    return {
      list: res.data.records || [],
      total: res.data.total || 0,
    };
  }
});
const { total, loading, dataList, pageSize, currentPage } = tableState;
const { getList } = tableMethods;

const currentNodeKeys = ref();



const isHighlyCriticalOptions = computed(() => {
  return dictionaryStore.dictionaries.get(
    dictionaryStore.DICTIONARY_TYPES.YORN
  ) || [];
});
// 自主可控等级
const controllableOptions = computed(() => {
  return (
    dictionaryStore.dictionaries.get(
      dictionaryStore.DICTIONARY_TYPES.INDEPENDENT_CONTROL_LEVEL
    ) || []
  );
});


const loadingLock = ref(false)
const lastRequestKey = ref('') // 记录最后一次请求的key
// 防抖的获取列表方法
const getListDebounced = debounce(async () => {
  if (loadingLock.value || loading.value) return

  const currentKey = deviceTreeStore.currentNodeKey
  if (!currentKey) {
    dataList.value = []
    total.value = 0
    return
  }

  // 如果和上次请求的key相同，且数据已存在，则不重复请求
  if (lastRequestKey.value === currentKey && dataList.value.length > 0) {
    return
  }

  loadingLock.value = true
  lastRequestKey.value = currentKey

  try {
    await getList()
  } finally {
    loadingLock.value = false
  }
}, 300)
// ============ 监听器 ============

/**
 * 监听store中的currentNodeKey变化
 */
watch(
  () => deviceTreeStore.currentNodeKey,
  (newKey, oldKey) => {
    currentNodeKey.value = newKey
    currentNodeKeys.value = newKey

    // 只有当节点真正变化时才刷新数据
    if (newKey && newKey !== oldKey) {
      currentPage.value = 1

      dataList.value = [] // 清空旧数据
      getListDebounced()
    }
  },
  { immediate: true }
)

/**
 * 监听当前树节点，更新节点名称
 */
watch(
  () => deviceTreeStore.currentTreeNode,
  (node) => {
    currentNodeName.value = node?.deviceName || ""
  }
)
const crudSchemas = reactive<CrudSchema[]>([
    {
    field: "selection",
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: { type: "selection", hidden: true },
  },
  {
    field: "index",
    label: "序号",
    form: { hidden: true },
    search: { hidden: true },
    detail: { hidden: true },
    table: { type: "index" },
  },
  {
    field: "account",
    label: "所属设备",
    width: 90,
    search: { hidden: true },
    form: {
      component: "Input",
      value: currentNodeName.value,
      componentProps: {
        placeholder: "请输入所属设备",
        disabled: true,
      },
    },
    table: { hidden: true },
  },
  {
    field: "productCategory",
    label: "基础产品类别",
    width: 120,
    form: {
      formItemProps: {
        rules: [
          { required: true, message: "请输入基础产品类别" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入基础产品类别" },
        ],
      },
      componentProps: { placeholder: "请输入基础产品类别" },
    },
    search: { hidden: true },
  },
  {
    field: "basicProductName",
    label: "基础产品名称",
    // width: 120,
    form: {
      formItemProps: {
        rules: [
          { required: true, message: "请输入基础产品名称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入基础产品名称" },
        ],
      },
      componentProps: { placeholder: "请输入基础产品名称" },
      colProps: { span: 24 },
    },
    detail: { span: 24 },
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "基础产品名称" },
    },
  },
    {
    field: "productVersion",
    label: "产品版本",
    width: 100,
    search: {
      component: "Input",
      label: "",
      hidden: true,
      componentProps: { placeholder: "版本" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入版本" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入版本" },
        ],
      },
      componentProps: { placeholder: "请输入版本" },
    },
  },
    {
    field: "launchTime",
    label: "产品上市时间",
    width: 80,
    search: {
      component: "Input",
      label: "",
      hidden: true,
      componentProps: { placeholder: "产品上市时间" },
    },
    form: {
      component: "DatePicker",
      formItemProps: {
        rules: [{ required: true, message: "请选择产品上市时间" }],
      },
      componentProps: {
        type: "month",
        valueFormat: "YYYY-MM", // 添加这一行
        placeholder: "请输入产品上市时间",
      },
    },
    table: { hidden: true },
  },
  // {
  //   field: "manufacturer",
  //   label: "生产厂商",
  //   width: 150,
  //   search: {
  //     component: "Input",
  //     label: "",
  //     hidden: false,
  //     componentProps: { placeholder: "生产厂商" },
  //   },
  //   form: {
  //     component: "Input",
  //     formItemProps: {
  //       rules: [
  //         { required: true, message: "请输入生产厂商" },
  //         { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入生产厂商" },
  //       ],
  //     },
  //     componentProps: { placeholder: "生产厂商" },
  //   },
  // },


  {
    field: "quantityPerProduct",
    label: "单个设备使用该产品数量",
    width: 90,
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入单个设备使用该产品数量" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error("输入值不能低于 0"));
              }
              callback();
            },
          },
        ],
      },
      componentProps: {
        placeholder: "请输入单个设备使用该产品数量",
        min: 0,
        type: "number",
      },
    },
  },
  {
    field: "manufacturer",
    label: "国产基础产品研制单位",
    width: 170,
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "国产基础产品研制单位" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入国产基础产品研制单位" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入国产基础产品研制单位" },
        ],
      },
      componentProps: { placeholder: "请输入国产基础产品研制单位" },
    },
  },

  {
    field: "mainTechnicalIndicators",
    label: "主要技术指标",
    width: 90,
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入主要技术指标" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入主要技术指标" },
        ],
      },
      componentProps: { placeholder: "请输入主要技术指标" },
      colProps: { span: 24 },
    },
    detail: { span: 24 },
  },
    {
    field: "independentControlLevel",
    label: "自主可控等级",
    width: 120,
    search: {
      component: "Select",
      label: "自主可控等级",
      hidden: false,
      componentProps: {
        placeholder: "自主可控等级",
        options: controllableOptions,
      },
    },
    form: {
      component: "Select",
      value: "",
      formItemProps: {
        rules: [{ required: true, message: "请选择自主可控等级" }],
      },
      componentProps: { options: controllableOptions },
    },
  },
  {
    field: "adaptationRelationship",
    label: "产品适配关系",
    width: 90,
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入适配关系" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入适配关系" },
        ],
      },
      componentProps: { placeholder: "请输入适配关系" },
    },
    table: { hidden: true },
  },
  {
    field: "isCoreKeyProduct",
    label: "是否核心关键产品",
    width: 140,
    form: {
      component: "Select",
      value: "是",
      formItemProps: {
        rules: [{ required: true, message: "请选择是否核心关键产品" }],
      },
      componentProps: { options: isHighlyCriticalOptions },
    },
    search: {
      component: "Select",
      label: "是否核心关键产品",
      hidden: false,
      componentProps: {
        placeholder: "是否核心关键产品",
        options: isHighlyCriticalOptions,
      },
    },
  },
  {
    field: "referencePrice",
    label: "参考价格(万元)",
    width: 120,
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入参考价格" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error("输入值不能低于 0"));
              }
              callback();
            },
          },
        ],
      },
      componentProps: {
        type: "number",
        placeholder: "请输入参考价格",
        min: 0,
      },
    },
  },
  {
    field: "supplyCycle",
    label: "供货周期(周)",
    width: 120,
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: false, message: "请输入供货周期" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error("输入值不能低于 0"));
              }
              callback();
            },
          },
        ],
      },
      componentProps: {
        type: "number",
        placeholder: "请输入供货周期",
        min: 0,
      },
    },
  },
  {
    field: "isInIndependentCatalog",
    label: "是否进入自主可控目录",
    form: {
      component: "Select",
      value: "是",
      formItemProps: {
        rules: [{ required: true, message: "请选择是否进入自主可控目录" }],
      },
      componentProps: { options: isHighlyCriticalOptions },
    },
    search: { hidden: true },
    table: { hidden: true },
  },
  {
    field: "evaluationInstitution",
    label: "测评机构",
    width: 90,
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入测评机构" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入测评机构" },
        ],
      },
      componentProps: { placeholder: "请输入测评机构" },
    },
    table: { hidden: true },
  },
  {
    field: "testingInstitution",
    label: "检测机构",
    width: 90,
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入检测机构" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入检测机构" },
        ],
      },
      componentProps: { placeholder: "请输入检测机构" },
    },
    table: { hidden: true },
  },
  {
    field: "historicalApplication",
    label: "历史应用情况",
    width: 90,
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Input",
        colProps: { span: 24 },
      componentProps: { placeholder: "请输入历史应用情况" },
    },
      detail: { span: 24 },
  },
  {
    field: "singleLevelEquipmentName",
    label: "单机设备名称",
    width: 150,
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入单机设备名称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入单机设备名称" },
        ],
      },
      componentProps: { placeholder: "请输入单机设备名称" },
    },
  },
  {
    field: "devUnitPersonInCharge",
    label: "基础产品研制单位负责人",
    width: 80,
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入基础产品研制单位负责人" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入基础产品研制单位负责人" },
        ],
      },
      componentProps: { placeholder: "请输入基础产品研制单位负责人" },
    },
  },
  {
    field: "devUnitContactInfo",
    label: "基础产品研制单位联系人方式",
    width: 90,
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入基础产品研制单位联系方式" },
          { pattern: /^[0-9]{11}$/, message: "请输入正确的基础产品研制单位联系方式" },
        ],
      },
      componentProps: { placeholder: "请输入基础产品研制单位联系方式" },
    },
    detail: { span: 12 },
  },
  {
    field: "benchmarkImportName",
    label: "对标进口产品名称",
    // width: 140,
    search: { hidden: true },
    form: {
      component: "Input",

      componentProps: { placeholder: "请输入对标进口产品名称" },
    },
  },
  {
    field: "benchmarkImportVersion",
    label: "对标进口产品版本",
    width: 80,
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Input",

      componentProps: { placeholder: "请输入对标进口产品版本" },
    },
  },
  {
    field: "benchmarkImportManufacturer",
    label: "对标进口产品生产厂商",
    width: 150,
    search: {
      component: "Input",
      label: "",
      hidden: true,
      componentProps: { placeholder: "对标进口产品生产厂商" },
    },
    form: {
      component: "Input",

      componentProps: { placeholder: "请输对标进口产品生产厂商" },
    },
    table: { hidden: true },
  },
  {
    field: "benchmarkImportRegion",
    label: "对标进口产品国别/地区",
    width: 150,
    search: { hidden: true },
    form: {
      component: "Input",

      componentProps: { placeholder: "请输对标进口产品国别/地区" },
      colProps: { span: 24 },
    },
    table: { hidden: true },
    detail: { span: 24 },
  },
  {
    field: "basicProductUser",
    label: "基本产品使用人",
    width: 140,
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入基本产品使用人" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入基本产品使用人" },
        ],
      },
      componentProps: { placeholder: "请输入基本产品使用人" },
    },
  },
  {
    field: "userContactInfo",
    label: "基本产品使用人联系方式",
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Input",
      componentProps: { placeholder: "请输入基本产品使用人联系方式" },
      formItemProps: {
        rules: [
          { required: true, message: "请输入基本产品使用人联系方式" },
          { pattern: /^[0-9]{11}$/, message: "请输入正确的基本产品使用人联系方式" },
        ],
      },
      colProps: { span: 12 },
    },
  },
  {
    field: "remarks",
    label: "备注",
    width: 90,
    search: { hidden: true },
    detail: { span: 24 },
    form: {
      component: "Input",
      componentProps: {
        type: "textarea",
        rows: 3,
        placeholder: "请输入备注信息",
      },
      colProps: { span: 24 },
    },
    table: { hidden: true },
  },

  {
    field: "action",
    label: "操作",
    fixed: "right",
    form: {
      hidden: true,
    },
    detail: {
      hidden: true,
    },
    search: {
      hidden: true,
    },
    table: {
      width: 80,
      fixed: "right", // 这里也需要添加
      slots: {
        default: (data: any) => {
          const row = data.row ;
          return (
            <>
              <div style="display:flex;color: var(--el-color-primary)">

                <div class="flex-1 cursor-pointer" onClick={() => action(row, "detail")}>
                  {" "}
                  <el-icon>
                    <View />
                  </el-icon>
                  查看
                </div>

              </div>
            </>
          );
        },
      },
    },
  },
]);

const { allSchemas } = useCrudSchemas(crudSchemas);



const searchParams = ref({});
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = {
    ...params,
  }
  getList()
}

const dialogVisible = ref(false);
const dialogTitle = ref("");

const currentRow = ref();
const actionType = ref("");

const AddAction = () => {
  dialogTitle.value = "新增";

    currentRow.value = {
    account: currentNodeName.value
  };

  dialogVisible.value = true;
  actionType.value = "";
};


const delData = async (row?: any) => {

  ElMessageBox.confirm("是否确认删除?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const params ={
        id:row?.id
      }
      const res = await directAxios.post(
        "/cDomesticSoftwares/delete",
        params,
        {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          transformRequest: [
            (data) => {
              return data.toString(); // 确保转换为字符串
            },
          ],
        }
      );

      if (res.code === 200) {
        ElMessage.success("删除成功");
        getList();
      }
    })
    .catch(() => {});
};

const action = (row: any, type: string) => {
  dialogTitle.value = type === "edit" ? "编辑" : "查看";
  actionType.value = type;
const actualDeviceName = deviceTreeStore.getDeviceNameByCode(row.deviceCode);
  currentRow.value = {
    ...row,
    account: actualDeviceName, // 确保所属设备字段有值
  };
  dialogVisible.value = true;
};

const writeRef = ref<ComponentRef<typeof Write>>();

const saveLoading = ref(false);

const save = async () => {
  const write = unref(writeRef);
  const formData = await write?.submit();
  if (formData) {
    saveLoading.value = true;
    try {
      const res = await "/cDomesticSoftwares/save".post({
        ...formData,
        deviceCode: currentNodeKeys.value,
      //  account : currentNodeName.value
      });
      if (res) {
        currentPage.value = 1;
        getList();
      }
    } catch (error) {
      console.log(error);
    } finally {
      saveLoading.value = false;
      dialogVisible.value = false;
    }
  }
};

// 导入相关状态

const importLoading = ref(false);
const uploadRef = ref<UploadInstance>();
const selectedFile = ref<File | null>(null);
const handleFileChange = async (file: UploadFile) => {
  if (!file.raw) {
    return;
  }

  selectedFile.value = file.raw;

  // 立即开始导入
  importLoading.value = true;
  // ElMessage.info('开始导入文件...');

  try {

    // 调用导入API
    const formData = new FormData();
    formData.append('file', file.raw);
    formData.append('deviceCode', currentNodeKeys.value);

    const res = await "/cDomesticSoftwares/importByExcel".post(formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
      ElMessage.success('导入成功');
      getList(); // 刷新列表

  } catch (error: any) {
  ElMessage.warning(error.data.msg);


  } finally {


    importLoading.value = false;
    // 清空文件选择
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
    }
    selectedFile.value = null;
  }
};



const exportAction =async () => {
// console.log(import.meta.env.VITE_APP_API_URL);

window.location.href =import.meta.env.VITE_APP_API_URL+ "/cDomesticSoftwares/export";


};


// 添加监听器，监听树节点变化
// 在页面组件中添加深度监听



onMounted(async () => {
  await dictionaryStore.preloadCommonDictionaries();
   currentNodeName.value= deviceTreeStore.currentTreeNode?.deviceName

  // 如果store中已有选中的节点，立即加载数据
  // if (deviceTreeStore.currentNodeKey) {
  //   getList();
  // }
});
</script>

<style scoped lang="less">
.el-card {
  // overflow-x: auto;
  //  --el-card-border-color {

  //  }
}
.operIcon {
  width: 20px !important;
}
:deep(.el-divider--horizontal) {
  margin: 5px 0 15px 0;
}
.mb-10px {
  display: flex;

}
.opBtn-upload {
  display: inline-block;
  margin: 0 12px;
}
:deep(.el-card__body ){
  padding: 20px  0 !important;
}
</style>
